package com.jw.elasticsearch.springboot.index;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 索引生成
 */
@Service
@Slf4j
public class IndexBuilder {
    private static final String INDEX_NAME = "idx_test";
    @Autowired
    private ElasticsearchTemplate esTemplate;
    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引
     */
    public void createIndex() {
        StudentIndexType studentIndexType = new StudentIndexType();
        studentIndexType.setStuId(1L);
        studentIndexType.setName("李四");
        studentIndexType.setAge(18);
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(INDEX_NAME);
        try {
            CreateIndexResponse response = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            log.info("索引创建成功，{}", new String(response.index().getBytes(), StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
            log.error("索引创建失败：{}", e.getMessage());
        }
    }

    public void add() {
        //已过时
//        IndexRequest indexRequest = new IndexRequest(INDEX_NAME, "String", "3");
//        indexRequest.source("{\"name\":\"张三\",\"role\":\"老师\"}", XContentType.JSON);
        // source方式可多种多样，此处只是演示
        IndexRequest indexRequest = new IndexRequest(INDEX_NAME).id("4").source("{\"name\":\"张三\",\"role\":\"老师\", \"stuId\":\"4\"}", XContentType.JSON);
        //这里的json为存入ES的文档内容
        try {
            //RequestOptions在新方法中必须选择
            IndexResponse indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
            log.info("添加索引数据成功，返回状态：{}", indexResponse.status());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("添加索引数据失败：{}", e.getMessage());
        }
    }

    /**
     * 获取文档
     */
    public void getDocument() throws IOException {
        GetRequest request = new GetRequest(
                //索引名称
                INDEX_NAME,
                //文档id
                "1");
        //禁用源检索，默认情况下启用
        request.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE);

        String[] includes = new String[]{"张三"};
        String[] excludes = Strings.EMPTY_ARRAY;
        FetchSourceContext fetchSourceContext =
                new FetchSourceContext(true, includes, excludes);
        //为特定字段配置源包含
        request.fetchSourceContext(fetchSourceContext);
        //配置特定存储字段的检索(要求字段在映射中单独存储)
        request.storedFields("_source");
        GetResponse getResponse = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        //检索消息存储字段(要求该字段单独存储在映射中
//        String message = getResponse.getField("_source").getValue();
//        log.info("获取到的信息为：{}", message);
    }
}
